package team.wuyou.util.jdbc;

import java.sql.*;
import java.util.*;
public class JDBCUtil {
    private static JDBCUtil jdbcUtil;
    private static final Connection conn;
    static {
        try {
            Class.forName(Propertity.Driver);
            //获取链接
             conn = DriverManager.getConnection( Propertity.url, Propertity.username, Propertity.password);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        JDBCUtil jdbcUtil = JDBCUtil.getJdbcUtil();
        map.put("username","");
        List user = jdbcUtil.Query("user", map);
        System.out.println(user);
    }
    public List Query(String TableName, Map<String, Object> map) throws Exception {
        //列
        String sql="select * from "+TableName+" where 1+1 ";
        //and拼接
        sql = getAndSql(sql, map);
        //载体
        PreparedStatement ps = this.getStatement(sql);
        //获取where后的值
        List inputData = this.getInputData(map);
        //将值付给 ？
        this.setData(ps,inputData);
        //执行sql
        ResultSet rs = this.getexecuteQuery(ps);
        //获取返回值
        List data = this.getResultList(rs);
        //关闭流
        this.close(conn,ps,rs);
        return data;
    }
    public List updata(String TableName, Map<String, Object> map,Map<String, Object> map2) throws Exception {
        //更改内容
        Set<Map.Entry<String,Object>> set = map.entrySet();
        Iterator<String> iterator = map.keySet().iterator();
        String next = iterator.next();
        String sql = "update "+TableName+" set `"+next+"` = `"+next+"` ";
        //and拼接
        sql = getAndSql(sql, map);
        //载体
        PreparedStatement ps = this.getStatement(sql);
        //获取where后的值
        List inputData = this.getInputData(map);
        //将值付给 ？
        this.setData(ps,inputData);
        //执行sql
        ResultSet rs = this.getexecuteQuery(ps);
        //获取返回值
        List data = this.getResultList(rs);
        //关闭流
        this.close(conn,ps,rs);
        return data;
    }
    private List getInputData (Map<String, Object> map) throws SQLException {
        List list = new ArrayList();
        Set<Map.Entry<String,Object>> set =  map.entrySet();
        for (Map.Entry entry: set) {
            if (entry.getKey()!=""&&entry.getKey()!=null&&entry.getValue()!=null&&entry.getValue()!="") {
                list.add(entry.getValue());
            }
        }
        return list;
    }
    private String getAndSql (String sql,Map<String, Object> map) throws SQLException {
        Set<Map.Entry<String,Object>> set =  map.entrySet();
        for (Map.Entry entry: set) {
            if (entry.getKey()!=""&&entry.getKey()!=null&&entry.getValue()!=null&&entry.getValue()!="") {
                sql += "AND " + entry.getKey() + " = ? ";
            }
        }
        System.out.println(sql);
        return sql;
    }
    private String getAndInSql (String sql,Map<String, Object> map) throws SQLException {
        ArrayList<Object> list = new ArrayList<>();
        Set<Map.Entry<String,Object>> set =  map.entrySet();
        for (Map.Entry entry3: set) {
            if (entry3.getKey()!=""&&entry3.getKey()!=null&&entry3.getValue()!=null&&entry3.getValue()!="") {
                String[] value = entry3.getValue().toString().split(",");
                sql+=" And "+ entry3.getKey() +" in ( ? ";
                list.add(value[0]);
                for (int i = 1; i <value.length ; i++) {
                    sql+=", ? ";
                    list.add(value[i]);
                }
                sql+=   ""+" );";
            }
        }
        //sql=sql+" And "+ entry3.getKey() +" in ( ? )";
        System.out.println(sql);
        System.out.println(sql);
        return sql;
    }
    private String getDouHaoSql (String sql,Map<String, Object> map) throws SQLException {
        Set<Map.Entry<String,Object>> set =  map.entrySet();
        if (map.size()>0) {
            for (Map.Entry entry : set) {
                sql = sql +", " + entry.getKey() + " = ?  ";
            }
            sql += "where 1=1";
        }
        System.out.println(sql);
        return sql;
    }
    private ResultSet getexecuteQuery (PreparedStatement ps) throws SQLException {
        //执行sql
        ResultSet rs = ps.executeQuery();
        return rs;
    }
    private PreparedStatement getStatement (String sql) throws SQLException {
        //载体
        PreparedStatement ps = conn.prepareStatement(sql);
        return ps;
    }
    private List getResultList(ResultSet rs) throws SQLException {
        List data = new ArrayList();
        //获取元数据
        ResultSetMetaData metaData = rs.getMetaData();
        //统计列的数量
        int columnCount = metaData.getColumnCount();
        //列数
        //System.out.println("columnCount："+columnCount);
        //获取每一列的下一个数据是否有值
        while (rs.next()){
            Map map2 =new HashMap();
            for (int i = 1; i <= columnCount; i++) {
                //获取列名
                //user user=new user();
                String columnName = metaData.getColumnName(i);
                //输出列明
                //System.out.print("columnName:"+columnName);
                //根据列名获取
                Object object = rs.getObject(columnName);
                //列名为key键，信息为value输入map
                map2.put(columnName,object);
            }
            //每获取一行数据添加一次
            data.add(map2);
        }
        return data;
    }

    private  void setData(PreparedStatement ps,List list) throws SQLException {
        for (int i = 0; i < list.size(); i++) {
            ps.setObject(i+1,list.get(i));
        }
    }
    public static JDBCUtil getJdbcUtil(){
        if(jdbcUtil == null) {
            jdbcUtil = new JDBCUtil();
        }
        return jdbcUtil;
    }
    /**
     * @Description //TODO
     * @Date 2023/12/20 10:00
     * @Author xing
     * 关闭链接
     **/
    private void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if(resultSet != null){
            resultSet.close();
        }
        if(statement != null){
            statement.close();
        }
        if(connection != null){
            connection.close();
        }
    }
}
